package com.atguigu.gmall.scheduled.jobHandler;

import com.atguigu.gmall.scheduled.mapper.CartMapper;
import com.atguigu.gmall.scheduled.pojo.Cart;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class CartJobHandler {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CartMapper cartMapper;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final String EXCEPTION_KEY = "cart:exception";
    private static final String KEY_PREFIX = "cart:info:";

    @XxlJob("cartSyncDataJobHandler")
    public ReturnT<String> syncData(String param){

        // 1.读取redis中异常信息
        BoundSetOperations<String, String> setOps = this.redisTemplate.boundSetOps(EXCEPTION_KEY);

        // 2.遍历异常用户id列表Set
        String userId = setOps.pop();
        while (StringUtils.isNotBlank(userId)){
            // 3.清空当前userId用户mysql中的购物车
            this.cartMapper.delete(new UpdateWrapper<Cart>().eq("user_id", userId));

            // 4.读取redis中该用户的购物车
            BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
            List<Object> cartJons = hashOps.values();
            if (CollectionUtils.isEmpty(cartJons)){
                // 同步下一个用户的购物车
                userId = setOps.pop();
                continue;
            }

            // 5.新增到mysql数据库
            cartJons.forEach(cartJson -> {
                try {
                    Cart cart = MAPPER.readValue(cartJson.toString(), Cart.class);
                    this.cartMapper.insert(cart);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            });

            userId = setOps.pop();
        }
        return ReturnT.SUCCESS;
    }
}
